package house

import (
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"server/db"
)

type HouseDao struct {
	db *db.MongoMiddleware
}

func NewHouseDao() *HouseDao {
	return &HouseDao{
		db: db.Db,
	}
}
func (h *HouseDao) HouserInfo(userId string) (House, error) {
	filter := bson.M{"user_id": userId}
	var houseInfo House
	err := h.db.FindOne(TBL_HOUSER, filter, &houseInfo)
	if err != nil {
		return houseInfo, err
	}
	return houseInfo, nil
}
func (h *HouseDao) Insert(info House) error {
	err := h.db.Insert(TBL_HOUSER, info)
	if err != nil {
		return err
	}
	return nil
}

func (h *HouseDao) updateHouseInfo(userId string, houseId int32, info HouseInfo) (House, error) {
	filter := bson.M{"user_id": userId}
	var houseInfo House
	err := h.db.FindOne(TBL_HOUSER, filter, &houseInfo)
	if err != nil {
		return houseInfo, err
	}
	houseInfo.HouseList[houseId] = info
	update := map[string]interface{}{
		"$set": map[string]interface{}{"house_list": houseInfo.HouseList},
	}
	err = h.db.Update(TBL_HOUSER, filter, update)
	if err != nil {
		return houseInfo, err
	}
	return houseInfo, nil
}
func (h *HouseDao) updateFurnitureInfo(userId string, houseId int32, info FurnitureInfo) (House, error) {
	filter := bson.M{"user_id": userId}
	var houseInfo House
	err := h.db.FindOne(TBL_HOUSER, filter, &houseInfo)
	if err != nil {
		return houseInfo, err
	}
	houseListInfo := houseInfo.HouseList[houseId]
	houseListInfo.FurnitureList[info.FurnitureId] = info
	update := map[string]interface{}{
		"$set": map[string]interface{}{"house_list": houseInfo.HouseList},
	}
	err = h.db.Update(TBL_HOUSER, filter, update)
	if err != nil {
		return houseInfo, err
	}
	return houseInfo, nil
}
func (h *HouseDao) houseInfoByHouseId(userId string, houseId int32) (HouseInfo, error) {
	filter := bson.M{"user_id": userId}
	var houseList House
	var houseInfo HouseInfo
	err := h.db.FindOne(TBL_HOUSER, filter, &houseList)
	if err != nil {
		return houseInfo, err
	}
	houseInfo, ok := houseList.HouseList[houseId]
	if !ok {
		return houseInfo, fmt.Errorf("没有该房屋")
	}
	return houseInfo, nil
}
func (h *HouseDao) furnitureInfoByHouseId(userId string, houseId, furnitureId int32) (FurnitureInfo, error) {
	filter := bson.M{"user_id": userId}
	var houseList House
	var houseInfo HouseInfo
	var furnitureInfo FurnitureInfo
	err := h.db.FindOne(TBL_HOUSER, filter, &houseList)
	if err != nil {
		return furnitureInfo, err
	}
	houseInfo, ok := houseList.HouseList[houseId]
	if !ok {
		return furnitureInfo, fmt.Errorf("没有该房屋")
	}
	furnitureInfo, ok = houseInfo.FurnitureList[furnitureId]
	if !ok {
		return furnitureInfo, fmt.Errorf("未解锁该家具")
	}
	return furnitureInfo, nil
}
